﻿using System.Linq;
using System.Linq.Expressions;

namespace System.Web.Mvc
{
	public static partial class Holovacs
	{
		public static HtmlString ReadOnlyFor<TModel, TProperty>(
			this HtmlHelper<TModel> htmlHelper,
			Expression<Func<TModel, TProperty>> expression,
			object htmlAttributes) where TModel : class
		{
			//initialize values
			var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
			var propertyName = metaData.PropertyName;
			var propertyValue = htmlHelper.ViewData.Eval(propertyName).ToStringOrEmpty();
			var returnText = string.Empty;

			//build the element
			if (htmlHelper.ViewData.Eval(propertyName) is bool)
			{
				var val = (bool)htmlHelper.ViewData.Eval(propertyName);
				returnText = string.Format("<input type=\"checkbox\" id=\"{0}\" name=\"{0}\"{1} readonly=\"readonly\" disabled=\"disabled\"",
					propertyName, val ? " checked=\"checked\"" : string.Empty);
			}
			else
			{
			returnText = string.Format("<input type=\"text\" id=\"{0}\" name=\"{0}\" value=\"{1}\" readonly=\"readonly\"",
				propertyName, HttpUtility.HtmlEncode(propertyValue));
			}

			if (htmlAttributes != null)
			{
				foreach (var kvp in htmlAttributes.GetType().GetProperties()
				 .ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null)))
				{
					returnText += string.Format(" {0}=\"{1}\"", HttpUtility.HtmlEncode(kvp.Key),
					 HttpUtility.HtmlEncode(kvp.Value.ToStringOrEmpty()));
				}
			}
			returnText += ">\n";
			return new HtmlString(returnText);
		}

		public static HtmlString ReadOnlyFor<TModel, TProperty>(
			this HtmlHelper<TModel> htmlHelper,
			Expression<Func<TModel, TProperty>> expression) where TModel : class
		{
			return htmlHelper.ReadOnlyFor(expression, null);
		}
	}
}
